/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.autoescola.core.dao.security.user.impl;

import com.autoescola.core.dao.DaoImpl;
import com.autoescola.core.dao.DefaultDao;
import com.autoescola.core.dao.security.user.UserDao;
import com.autoescola.core.entity.security.User;
import com.autoescola.core.util.security.LogonUtils;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;


/**
 *
 * @author leonardo luz fernandes
 * @version 0.1
 * @since 01/11/2010
 */

@DefaultDao
@DaoImpl
public class UserDaoImpl implements UserDao {

    @PersistenceContext(name="alexandria-pu")
    private EntityManager entityManager;

    //@PersistenceUnit(name="")
    //private Object name;
    
    
    @Override
    public User logon(String username, String password) throws Exception {
        
        UserLogonUtils ulu = new UserLogonUtils(entityManager);
        boolean authenticated = ulu.authenticate(username, password);
        
        if( authenticated == false ){
            throw new Exception("Invalid username or password.");
        }//end if
        
        return ulu.getUser();
        
    }//end method

    @Override
    public User logon(User user) throws Exception {
        
        UserLogonUtils ulu = new UserLogonUtils(entityManager);
        boolean authenticated = ulu.authenticate( user.getUsername() , user.getPassword() );
        
        if( authenticated == false ){
            throw new Exception("Invalid username or password.");
        }//end if        
        
        user = ulu.getUser();
        user.setLogonAt( new Date() );
        entityManager.persist( user );
        entityManager.flush();
        
        return user;
        
    }//end method

    @Override
    public boolean logout(String username, String password) throws Exception {
       
        UserLogonUtils ulu = new UserLogonUtils(entityManager);
        boolean authenticated = ulu.authenticate(username, password); 
        
        if( authenticated ){
        
            User user = ulu.getUser();
            user.setLogoutAt( new Date( System.currentTimeMillis() ) );
            user.setAccountEnable( true );
            entityManager.persist( user );
            entityManager.flush();
            entityManager.detach( user );
        
        }//end if
        
        return authenticated;
        
    }//end method

    @Override
    public boolean logout(User user) throws Exception {

        UserLogonUtils ulu = new UserLogonUtils(entityManager);
        boolean authenticated = ulu.authenticate( user.getUsername() , user.getPassword() ); 
        
        if( authenticated ){
        
            user = ulu.getUser();
            user.setLogoutAt( new Date( System.currentTimeMillis() ) );
            user.setAccountEnable( true );
            entityManager.persist( user );
            entityManager.flush();
            entityManager.detach( user );
        
        }//end if
        
        return authenticated ;        
        
    }//end method

    @Override
    public User create( User user ) throws Exception {
        
         //Verificar se ja existe um usuario cadastrado primeiro.
        
         UserLogonUtils ulu = new UserLogonUtils(entityManager);
         ulu.createUser( user.getUsername() , user.getPassword() );
         User nUser = ulu.getUser();
         
         user.setSalt( nUser.getSalt() );
         user.setPassword( nUser.getPassword() );
         user.setCreatedAt( new Date( System.currentTimeMillis() ) );
         user.setAccountEnable( true );
        
         entityManager.persist( user );
         entityManager.flush();
         
         return user;
        
    }//end method

    
    @Override
    public boolean delete( String username , String password ) throws Exception {
    
        UserLogonUtils ulu = new UserLogonUtils(entityManager);
        boolean authenticated = ulu.authenticate( username , password );     
        
        if( authenticated ){
        
            //Excluir fisicamente? Sim/Nao
            User user = ulu.getUser();
            user.setAccountEnable( false );
            
            entityManager.persist( user );
            entityManager.flush();
            entityManager.detach( user );
            
            return true;
            
        }//end if
        
        
        return authenticated ;
        
    }//end method
    
    @Override
    public boolean delete(User user) throws Exception {
       
         UserLogonUtils ulu = new UserLogonUtils(entityManager);
         boolean authenticated = ulu.authenticate( user.getUsername() , user.getPassword() ); 
       
         if( authenticated ){

            //Excluir fisicamente? Sim/Nao
            user.setAccountEnable( false );
            entityManager.persist( user );
            entityManager.flush();
            entityManager.detach( user );
            
            return true;
             
                      
         }//end if
         
         return authenticated;
         
    }//end method
    
    @Override
    public User update( User user ) throws Exception {
        
         UserLogonUtils ulu = new UserLogonUtils(entityManager);
         boolean authenticated = ulu.authenticate( user.getUsername() , user.getPassword() ); 
       
         if( authenticated ){
             this.entityManager.persist( user );
             
         }//end if
        
        return user;
        
    }//end method
    
    @Override
    public User changePassword( String username , String oldPassword , String newPassword ) throws Exception {

         UserLogonUtils ulu = new UserLogonUtils(entityManager);
         ulu.newPassword(username, oldPassword, newPassword);
        
        return null;
        
    }//end method
    
    
    
    private class UserLogonUtils extends LogonUtils {
    
        private EntityManager entityManager;
        
        public UserLogonUtils( EntityManager entityManager ){
            this.entityManager = entityManager ;
        }//end konstructor
 
        @Override
        protected User load( String username ) {
            
            String statement = "SELECT u FROM " + User.class.getName() + " u WHRE u.username = :pUsername and u.accountEnable = true " ;
            TypedQuery<User> query = entityManager.createQuery( statement , User.class );
            query.setParameter("pUsername", username );
            
            return query.getSingleResult();
            
        }//end method
        
    }//end method

}//end klazz
